import traceback
from extensions import db
from models.user import User
from extensions import redis_store

def is_user_exists(email:str) -> bool:
    """通过邮箱判断用户是否存在
    
    Parameters:
        email: 用户邮箱
    
    Returns:
        bool: 用户是否存在
    """
    try:
        user = User.query.filter_by(email=email).first()
        return user is not None
    except Exception as e:
        print(f"查询用户 {email} 失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        return False

def create_user(email:str)-> None:
    """创建用户
    
    Parameters:
        email: 用户邮箱
    """
    try:
        new_user = User(email=email)
        db.session.add(new_user)
        db.session.commit()
        print(f"用户 {email} 创建成功")
    except Exception as e:
        db.session.rollback()
        print(f"创建用户 {email} 失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e
  
def get_user(email:str) -> User:
    """通过邮箱获取用户信息
    
    Parameters:
        email: 用户邮箱
    
    Returns:
        User: 用户对象
    """
    try:
        user = User.query.filter_by(email=email).first()
        if user is None:
            raise ValueError(f"用户 {email} 不存在")
        return user
    except Exception as e:
        print(f"获取用户 {email} 失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e

def delete_user(email:str) -> None:
    """删除用户
    
    Parameters:
        email: 用户邮箱
    """
    try:
        user = User.query.filter_by(email=email).first()
        if user:
            db.session.delete(user)
            db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(f"删除用户 {email} 失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e
    
def update_user(email:str, **kwargs) -> None:
    """更新用户信息
    
    Parameters:
        email: 用户邮箱
        kwargs: 更新的字段和对应的值
    """
    try:
        user = User.query.filter_by(email=email).first()
        if user is None:
            raise ValueError(f"用户 {email} 不存在")
        for key, value in kwargs.items():
            setattr(user, key, value)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(f"更新用户 {email} 失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e